package com.fcg.redis.topone.controller;

import com.fcg.redis.rediscommon.bean.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author FCG
 */
@Slf4j
@RestControllerAdvice("com.fcg.redis.topone.controller")
public class ControllerExHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseBean handleArgsEx(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        ObjectError error = result.getAllErrors().get(0);
        String msg = error.getDefaultMessage();
        log.debug("request params error:{}", msg);
        return ResponseBean.builder().code("40000").msg(msg).success(false).build();
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseBean handleArgsEx(IllegalArgumentException ex) {
        String msg = "参数异常:" + ex.getMessage();
        log.debug(msg);
        return ResponseBean.builder().code("40000").msg(msg).success(false).build();
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResponseBean handleArgsEx(Exception ex) {
        String msg = "系统异常:" + ex.getMessage();
        log.info(msg, ex);
        return ResponseBean.builder().code("50000").msg(msg).success(false).build();
    }
}
